#include <input_manager.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>          
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define Server_port 8888


static int g_sock;


static int NetinputInin(void)
{
    int iRet;
    struct sockaddr_in tsocketaddr;//使用sockaddr这个结构体，命名为tsocketaddr 
//socket创建一个句柄，如果返回值为-1则失败
    g_sock = socket(AF_INET, SOCK_DGRAM,0);//AF_INET表示ipv4，SOCK_DGRAM表示启动UDP连接
    if (-1 == g_sock)
    {
        printf("socket error\n");
        return -1;
    }
 
 
//使用sockaddr_in这个结构体，使用bind函数写入服务器的ip端口，与句柄绑定
    tsocketaddr.sin_family = AF_INET;//ipv4
    tsocketaddr.sin_addr.s_addr = INADDR_ANY;//本机的所有ip
    tsocketaddr.sin_port = htons(Server_port);//需要监听的端口host to nets转换成网络信号
    memset(tsocketaddr.sin_zero, 0, 8);//作用是将某一块内存中的内容全部设置为指定的值，把tsocketaddr.sin_zero的8位置0
    iRet = bind(g_sock, (const struct sockaddr *)&tsocketaddr,sizeof(struct sockaddr));//sock为 socket 函数调用返回的文件描述符，使 用 另 外 一 个 结 构 (struct 
//sockaddr_in 来代替，该结构体主要包含ip和端口， sockaddr结构的长度
//若bind函数的返回值为-1，则绑定失败
    if (-1 == iRet)
    {
        printf("bind error\n");
        return -1;
    }
 
 
    return 0;
}

static int NetinputExit(void)
{
    close(g_sock);
    return 0;
}


static int GetNetinputEvent(PInputEvent ptInputEvent)
{ 
    unsigned int addlen = sizeof(struct sockaddr);
    int recvlen;
    char aRecbuffer[1000] ;
    struct sockaddr_in tclientaddr;//使用sockaddr这个结构体，命名为tclientaddr

    addlen = sizeof(struct sockaddr);//获取struct sockaddr的大小

    recvlen = recvfrom(g_sock,aRecbuffer,999,0,(struct sockaddr*)&tclientaddr,&addlen);//接受最多999位数据
    if(recvlen > 0)
    {
        aRecbuffer[recvlen] ='\0';
//    printf("get mes from%d:%s\n",inet_ntoa(tclientaddr.sin_addr),Recbuffer);//接受到数据时打印出来
        ptInputEvent->iType   = INPUT_TYPE_NET;
        gettimeofday(&ptInputEvent->tTime,NULL);
        strncpy(ptInputEvent->str,aRecbuffer,1000);
        ptInputEvent->str[999] = '\0';
        return 0;
    }    
    else
    {
        return -1;
    }
}


static InputDevice g_tNetinputDev  ={
    .name = "Netinput",
    .GetInputEvent = GetNetinputEvent,
    .InputInin     = NetinputInin,
    .InputExit     = NetinputExit,  
};

void NetInPutDevRegister(void)
{
    RegisterInPut(&g_tNetinputDev); 
}



#if 0

int main(int argc, char **argv)
{
    InputEvent event;
    int ret;
    g_tNetinputDev.InputInin();

    while(1)
    {
        ret = g_tNetinputDev.GetInputEvent(&event);
        if(ret)
        {
            printf("Get Event Error\n");
            return -1;
        }
        else
        {
            printf("Type = %d\n",event.iType);
            printf("Press = %s\n",event.str);
        }
    }
    return 0;
}
#endif